package com.exercise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exercise.common.ServiceException;
import com.exercise.dto.SetmealDto;
import com.exercise.entity.Setmeal;
import com.exercise.entity.SetmealDish;
import com.exercise.mapper.SetmealMapper;
import com.exercise.service.SetmealDishService;
import com.exercise.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 陈凯
 * @create 2023-03-07-11:53
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);
        //保存套餐菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存菜品和套餐
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 以id删除套餐表以及关联表
     * @param ids
     */
    @Transactional
    @Override
    public void deleteSetmeal(List<Long> ids) {
        //判断套餐是否启售
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId, ids).eq(Setmeal::getStatus, 1);
        int count = this.count(setmealLambdaQueryWrapper);
        if (count > 0){
            throw new ServiceException("套餐正在售卖中，不能删除");
        }
        //可以删除，先删setmeal表
        this.removeByIds(ids);
        //再删关联表setmeal_dish
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
